<template>
  <div>
    <h2>用户列表</h2>
    <!-- <button @clcik="">添加</button> -->
    <router-link to="/users/add">添加</router-link>
    <table border="1">
      <thead>
        <tr>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="u in users" :key="u.id">
          <td>{{ u.name }}</td>
          <td>{{ u.age }}</td>
          <td>{{ u.gender }}</td>
          <td>
            <button @click="deleteUser(u.id)">删除</button>
            <router-link :to="'/users/edit?id=' + u.id">编辑</router-link>
          </td>
        </tr>
      </tbody>
    </table>

    <div class="pagenation">
      <ul>
        <li v-if="activePage > 1" @click="getUsers(activePage - 1)">←</li>
        <li :class="{ active: activePage === i }" @click="getUsers(i)" v-for="i in pagesCount">{{ i }}
        </li>
        <li v-if="activePage < pagesCount" @click="getUsers(activePage + 1)">→</li>
      </ul>
    </div>
  </div>
</template>
<script>
import axios from 'axios';

const request = axios.create({
  baseURL: 'http://127.0.0.1:8081'
});

export default {
  data() {
    return {
      users: [],
      totalCount: 0,
      pageSize: 5,
      activePage: 1
    };
  },
  created() {
    this.getUsers();
  },
  computed: {
    pagesCount() {
      return Math.ceil(this.totalCount / this.pageSize);
    }
  },
  methods: {
    async deleteUser(id) {
      if (confirm('确定删除吗？') === false) return;
      await request.delete(`/users/${id}`);
      this.getUsers();
    },
    async getUsers(page = 1) {
      this.activePage = page;
      const { data, headers } = await request.get('/users', {
        params: {
          _page: page,
          _limit: this.pageSize
        }
      });
      this.users = data;
      this.totalCount = headers['x-total-count'];
    }
  }
};
</script>
<style lang="scss">
.pagenation {
  ul {
    padding: 0;
    margin: 0;
    display: flex;
    flex-wrap: wrap;

    li {
      width: 30px;
      height: 30px;
      justify-content: center;
      align-items: center;
      border: 1px solid;
      display: flex;
      cursor: pointer;

      &:hover {
        background-color: beige;
      }

      &.active {
        background-color: beige;
      }

    }
  }
}
</style>